package client

import (
	"chatting/model"
	"fmt"
	"github.com/gogf/gf/v2/net/gtcp"
	"log"
	"sync"
)

type Client struct {
	*gtcp.Conn

	sendChan chan model.IMessage
	//注，ping pong消息不往chan里发
	receiveChan chan model.IResMessage
	//与chat有关的操作加锁,如果在聊天界面接受消息的协程收到了PlainRes要主动放弃锁，并且把消息放回去
	mu sync.Mutex
}

func NewClient() *Client {
	c := new(Client)
	conn, err := gtcp.NewConn("127.0.0.1:8088")

	if err != nil {
		panic(err)
	}
	fmt.Println("连接服务器成功？")
	c.Conn = conn
	c.sendChan = make(chan model.IMessage)
	c.receiveChan = make(chan model.IResMessage)
	return c
}

func (c *Client) Run() {
	go c.Send(c.Conn)
	go c.Receive(c.Conn)
	log.Println("连接服务器成功")
}

func (c *Client) Send(conn *gtcp.Conn) {
	for {
		select {
		case msg := <-c.sendChan:
			c.SendPkg(msg.Package())
		}
	}
}

func (c *Client) Receive(conn *gtcp.Conn) {
	for {
		pkg, err := conn.RecvPkg()
		if err != nil {
			log.Println(err)
		}
		resMessage := model.UnPackageToResMessage(pkg)
		fmt.Println("客户端收到消息", resMessage)

		c.receiveChan <- resMessage
	}
}
